package com.cmy.framework_widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.ceil

/**
 * Created by goldze on 2020/4/14
 * Email: goldze@126.com
 * Des:根据宽高自适应，但是在列表中，会导致算力提高，出现卡顿现象（不适用于列表中）
 */
class ResizableImageView : AppCompatImageView {
    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    )

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        drawable?.let {
            // ceil not round - avoid thin vertical gaps along the left/right edges
//            int width = MeasureSpec.getSize(widthMeasureSpec);
//            //高度根据使得图片的宽度充满屏幕计算而得
//            int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
//            setMeasuredDimension(width, height);
            val height = MeasureSpec.getSize(heightMeasureSpec)
            val width =
                ceil((height.toFloat() * it.intrinsicWidth.toFloat() / it.intrinsicHeight.toFloat()).toDouble())
                    .toInt()
            Log.e("TAG", "width:$width,height:$height")
            setMeasuredDimension(width, height)
        } ?: super.onMeasure(widthMeasureSpec, heightMeasureSpec)


    }
}